package com.hdy.javachatroomdemo.Controller;

import com.hdy.javachatroomdemo.Model.User;
import com.hdy.javachatroomdemo.Model.UserProperties;
import com.hdy.javachatroomdemo.Service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/chatRoom")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserProperties userProperties;
    @PostMapping("/login")
    public User login(String username, String password, HttpServletRequest res) {
        User user=userService.loginGetUser(username, password,res);
        return user;
    }

    @PostMapping("/register")
    public User register(String username, String password) {
        User user=userService.registerGetUser(username, password);
        return user;
    }

    @GetMapping("/getUser")
    public User getUser(HttpServletRequest req) {
        //这里不从数据库中拿数据,直接在controller层进行逻辑判断就行了
        HttpSession session= req.getSession(false);
        if(session==null){
            //会话对象为空,用户还未登录
            System.out.println("[UserController:getUser]:会话对象为空");
            return new User();
        }
        User user=(User)session.getAttribute(userProperties.getSession().getKey());
        if(user==null){
            //session表中user为空
            System.out.println("[UserController:getUser]:session表中user为空");
            return new User();
        }
        System.out.println(user);
        return user;
    }

}
